package com.example.fangyimanagement;

import com.example.fangyimanagement.core.LoginUser;
import com.example.fangyimanagement.core.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/hsjcManage")
public class hsjcManageController {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 添加核酸检测的数据
     * @param param
     * @return
     */
    @RequestMapping("/addHsjc")
    public Result<Void> addHsjc(@RequestBody Map<String, String> param) {
        String sfz = param.get("sfz");
        String name = param.get("name");
        String districtCode = param.get("districtCode");
        String hsjcd = param.get("hsjcd");
        String remark = param.get("remark");
        //        操作数据库
        String sql = "insert into hsjc_result (sfz, name, jc_time, district_code, jc_jcd, remark) " +
                "values (?, ?, CURRENT_TIME, ?, ?, ?)";
        int rows = this.jdbcTemplate.update(sql, sfz, name, districtCode, hsjcd, remark);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("添加失败");
        }
    }

    /**
     * 删除一条核酸检测的数据
     * @param param
     * @return
     */
    @RequestMapping("/deleteHsjc")
    public Result<Void> deleteHsjc(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        //        操作数据库
        int rows = this.jdbcTemplate.update("delete from hsjc_result where id =?", id);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("删除失败");
        }
    }

    /**
     * 修改一条核酸检测的数据
     * @param param
     * @return
     */
    @RequestMapping("/updateHsjc")
    public Result<Void> updateHsjc(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        String sfz = param.get("sfz");
        String name = param.get("name");
        String districtCode = param.get("districtCode");
        String hsjcd = param.get("hsjcd");
        String remark = param.get("remark");
        //        操作数据库
        String sql = "update hsjc_result set sfz=?, name=?, district_code=?, jc_jcd=?, remark=? where id =?";
        int rows = this.jdbcTemplate.update(sql, sfz, name, districtCode, hsjcd, remark, id);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("编辑失败");
        }
    }

    /**
     * 修改核酸检测结果
     * @param param
     * @return
     */
    @RequestMapping("/updateHsjcResult")
    public Result<Void> updateHsjcResult(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        String result = param.get("result");
        //        操作数据库
        String sql = "update hsjc_result set jc_result=?, report_time=current_time where id =?";
        int rows = this.jdbcTemplate.update(sql, result, id);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("操作失败");
        }
    }

    /**
     * 设置症状类型
     * @param param
     * @return
     */
    @RequestMapping("/updateHsjcStatus")
    public Result<Void> updateHsjcStatus(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        String result = param.get("result");
        //        操作数据库
        String sql = "update hsjc_result set zz_type=? where id =?";
        int rows = this.jdbcTemplate.update(sql, result, id);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("操作失败");
        }
    }

    /**
     * 查询核酸检测结果列表
     * @param param
     * @return
     */
    @RequestMapping("/hsjcList")
    public Result<List<Map<String, Object>>> hsjcList(@RequestBody Map<String, String> param, LoginUser loginUser) {
        String account = loginUser.getAccount();
        List<Map<String, Object>> accountRoleOrgList = this.jdbcTemplate.queryForList("SELECT name, role_code, org_code FROM glpt_user WHERE account=?", account);
        /**
         * 根据登录人账号找到了角色和组织编码，查数据时就要做权限控制
         */
        if (accountRoleOrgList.size() > 0) {
            String accountRole = (String) accountRoleOrgList.get(0).get("role_code");
            String accountOrg = (String) accountRoleOrgList.get(0).get("org_code");
            int page = Integer.parseInt(param.get("page"));
            int size = Integer.parseInt(param.get("size"));
            String name = param.get("name");
            String sfz = param.get("sfz");
            String districtCode = param.get("districtCode");
            String hsjcd = param.get("hsjcd");
            String hsjcjg = param.get("hsjcjg");
            String status = param.get("status");
            String hsjcDateStart = param.get("hsjcDateStart");
            String hsjcDateEnd = param.get("hsjcDateEnd");
            String reportDateStart = param.get("reportDateStart");
            String reportDateEnd = param.get("reportDateEnd");
            List<Object> paramList = new ArrayList<>();
            String sql = "SELECT\n" +
                    "    hsjc_result.id AS id, hsjc_result.name, hsjc_result.sfz,\n" +
                    "    " +
                    "hsjc_result.jc_time AS jianceTime, hsjc_result.district_code AS districtCode,\n" +
                    "    glpt_org.org_name AS districtName, " +
                    "hsjc_result.jc_jcd AS jcd, hsjcd_data.name as jcdName, \n" +
                    "hsjc_result.jc_result AS jcResultCode,\n" +
                    "    IFNULL(d1.name, '-') AS jcResultName, hsjc_result.report_time AS reportTime,\n" +
                    "    " +
                    "hsjc_result.remark, hsjc_result.zz_type AS status, IFNULL(d2.name, '-') AS statusName\n" +
                    "FROM hsjc_result \n" +
                    "    JOIN glpt_org ON glpt_org.org_code = hsjc_result.district_code\n" +
                    "    LEFT JOIN comm_dict d1 ON d1.code = hsjc_result.jc_result\n" +
                    "    LEFT JOIN comm_dict d2 ON d2.code = hsjc_result.zz_type" +
                    "    \n" +
                    "    LEFT JOIN hsjcd_data ON hsjcd_data.id = hsjc_result.jc_jcd" +
                    " \n" +
                    "\n" +
                    "where 1=1";

            if (name != null && !name.isEmpty()) {
                sql = sql + " AND hsjc_result.name like '%" + name + "%'";
            }
            if (sfz != null && !sfz.isEmpty()) {
                sql = sql + " AND sfz like '%" + sfz + "%'";
            }
            if (districtCode != null && !districtCode.isEmpty()) {
                sql = sql + " AND hsjc_result.district_code = ?";
                paramList.add(districtCode);
            }
            if (hsjcd != null && !hsjcd.isEmpty()) {
                sql = sql + " AND hsjc_result.jc_jcd = ?";
                paramList.add(hsjcd);
            }
            if (hsjcjg != null && !hsjcjg.isEmpty()) {
                sql = sql + " AND hsjc_result.jc_result = ?";
                paramList.add(hsjcjg);
            }
            if (status != null && !status.isEmpty()) {
                sql = sql + " AND hsjc_result.zz_type = ?";
                paramList.add(status);
            }
            if (hsjcDateStart != null && !hsjcDateStart.isEmpty()) {
                sql = sql + " AND hsjc_result.jc_time >= ?";
                paramList.add(hsjcDateStart);
            }
            if (hsjcDateEnd != null && !hsjcDateEnd.isEmpty()) {
                sql = sql + " AND hsjc_result.jc_time <= ?";
                paramList.add(hsjcDateEnd);
            }
            if (reportDateStart != null && !reportDateStart.isEmpty()) {
                sql = sql + " AND hsjc_result.report_time >= ?";
                paramList.add(reportDateStart);
            }
            if (reportDateEnd != null && !reportDateEnd.isEmpty()) {
                sql = sql + " AND hsjc_result.report_time <= ?";
                paramList.add(reportDateEnd);
            }
            /**
             * 如果是区级管理员，就要只查本区的范围
             * 如果是核酸检测点管理员，只要查自己名下的
             */
            if (accountRole.equals("district_manager") && accountOrg != null) {
                sql = sql + " AND hsjc_result.district_code = ?";
                paramList.add(accountOrg);
            } else if (accountRole.equals("hsjcdManager")) {
                sql = sql + " AND hsjcd_data.manager_account = ?";
                paramList.add(account);
            }

            String countSql = "SELECT COUNT(1) FROM ("+ sql +") t";
            Integer count = this.jdbcTemplate.queryForObject(countSql, Integer.class, paramList.toArray());

            String querySql = sql + " ORDER BY hsjc_result.id LIMIT ?, ?";
            paramList.add((page - 1) * size);
            paramList.add(size);
            List<Map<String, Object>> hsjcjgList = this.jdbcTemplate.queryForList(querySql, paramList.toArray());

            return Result.success(hsjcjgList).setTotal(count);
        } else {
            return Result.failed("查询失败，请稍后再试");
        }
    }

    /**
     * 移动端用户查询自己的核酸检测记录
     * @param param
     * @return
     */
    @RequestMapping("/mobileUserHsjcList")
    public Result<List<Map<String, Object>>> mobileUserHsjcList(@RequestBody Map<String, String> param) {
            int page = Integer.parseInt(param.get("page"));
            int size = Integer.parseInt(param.get("size"));
            String name = param.get("name");
            String sfz = param.get("sfz");
            String districtCode = param.get("districtCode");
            String hsjcd = param.get("hsjcd");
            String hsjcjg = param.get("hsjcjg");
            String status = param.get("status");
            String hsjcDateStart = param.get("hsjcDateStart");
            String hsjcDateEnd = param.get("hsjcDateEnd");
            String reportDateStart = param.get("reportDateStart");
            String reportDateEnd = param.get("reportDateEnd");
            List<Object> paramList = new ArrayList<>();
            String sql = "SELECT\n" +
                    "    hsjc_result.id AS id, hsjc_result.name, hsjc_result.sfz,\n" +
                    "    " +
                    "hsjc_result.jc_time AS jianceTime, hsjc_result.district_code AS districtCode,\n" +
                    "    glpt_org.org_name AS districtName, " +
                    "hsjc_result.jc_jcd AS jcd, hsjcd_data.name as jcdName, \n" +
                    "hsjc_result.jc_result AS jcResultCode,\n" +
                    "    IFNULL(d1.name, '-') AS jcResultName, hsjc_result.report_time AS reportTime,\n" +
                    "    " +
                    "hsjc_result.remark, hsjc_result.zz_type AS status, IFNULL(d2.name, '-') AS statusName\n" +
                    "FROM hsjc_result \n" +
                    "    JOIN glpt_org ON glpt_org.org_code = hsjc_result.district_code\n" +
                    "    LEFT JOIN comm_dict d1 ON d1.code = hsjc_result.jc_result\n" +
                    "    LEFT JOIN comm_dict d2 ON d2.code = hsjc_result.zz_type" +
                    "    LEFT JOIN hsjcd_data ON hsjcd_data.id = hsjc_result.jc_jcd" +
                    " where 1=1";

            if (name != null && !name.isEmpty()) {
                sql = sql + " AND hsjc_result.name like '%" + name + "%'";
            }
            if (sfz != null && !sfz.isEmpty()) {
                sql = sql + " AND sfz like '%" + sfz + "%'";
            }
            if (districtCode != null && !districtCode.isEmpty()) {
                sql = sql + " AND hsjc_result.district_code = ?";
                paramList.add(districtCode);
            }
            if (hsjcd != null && !hsjcd.isEmpty()) {
                sql = sql + " AND hsjc_result.jc_jcd = ?";
                paramList.add(hsjcd);
            }
            if (hsjcjg != null && !hsjcjg.isEmpty()) {
                sql = sql + " AND hsjc_result.jc_result = ?";
                paramList.add(hsjcjg);
            }
            if (status != null && !status.isEmpty()) {
                sql = sql + " AND hsjc_result.zz_type = ?";
                paramList.add(status);
            }
            if (hsjcDateStart != null && !hsjcDateStart.isEmpty()) {
                sql = sql + " AND hsjc_result.jc_time >= ?";
                paramList.add(hsjcDateStart);
            }
            if (hsjcDateEnd != null && !hsjcDateEnd.isEmpty()) {
                sql = sql + " AND hsjc_result.jc_time <= ?";
                paramList.add(hsjcDateEnd);
            }
            if (reportDateStart != null && !reportDateStart.isEmpty()) {
                sql = sql + " AND hsjc_result.report_time >= ?";
                paramList.add(reportDateStart);
            }
            if (reportDateEnd != null && !reportDateEnd.isEmpty()) {
                sql = sql + " AND hsjc_result.report_time <= ?";
                paramList.add(reportDateEnd);
            }

            String countSql = "SELECT COUNT(1) FROM ("+ sql +") t";
            Integer count = this.jdbcTemplate.queryForObject(countSql, Integer.class, paramList.toArray());

            String querySql = sql + " ORDER BY hsjc_result.id DESC LIMIT ?, ?";
            paramList.add((page - 1) * size);
            paramList.add(size);
            List<Map<String, Object>> hsjcjgList = this.jdbcTemplate.queryForList(querySql, paramList.toArray());

            return Result.success(hsjcjgList).setTotal(count);
    }

    /**
     * 获取核酸检测结果的字典值
     * @param param
     * @return
     */
    @RequestMapping("/getHsjcDicts")
    public Result<List<Map<String, Object>>> getHsjcDicts(@RequestBody Map<String, String> param) {
        String sql = "SELECT * FROM comm_dict";
        List<Map<String, Object>> hsjcjgList = this.jdbcTemplate.queryForList(sql);
        return Result.success(hsjcjgList);
    }

    /**
     * 获取核酸检测点列表的code和name
     * @param param
     * @return
     */
    @RequestMapping("/getHsjcdDicts")
    public Result<List<Map<String, Object>>> getHsjcdDicts(@RequestBody Map<String, String> param) {
        String orgCode = param.get("orgCode");
        String range = param.get("range");
        List<Object> paramList = new ArrayList<>();
        String sql = "SELECT id AS code, name FROM hsjcd_data WHERE 1=1";
        if (orgCode != null && !orgCode.isEmpty()) {
            sql = sql + " AND district_code = ?";
            paramList.add(orgCode);
        }
        if (range != null && !range.isEmpty() && range.equals("open")) {
            sql = sql + " AND status = 'true'";
        }
        List<Map<String, Object>> hsjcdList = this.jdbcTemplate.queryForList(sql, paramList.toArray());
        return Result.success(hsjcdList);
    }
}
